package com.liuyang.homework.Activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.liuyang.homework.Bean.News;
import com.liuyang.homework.Bean.NewsLab;
import com.liuyang.homework.R;
import com.liuyang.homework.Util.CTAS;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Vector;

import static com.liuyang.homework.Util.CTAS.isChinese;


/**
 * Created by liuyang on 2017/1/14.
 */

public class NewsDetailActivity extends AppCompatActivity {

    private static final String TAG = "NewsDetailActivity";

    private TextView tvTitle,tvContent,tvFrom,tvUrl,tvTime,tvKeyWords;
    View btDelete,btSave,btGetKeyWords;
    News news;
    ImageView ivImage;
    Toolbar toolbar;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news_detail);

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);

        ivImage= (ImageView) findViewById(R.id.iv_news_image);

        tvContent= (TextView) findViewById(R.id.tv_news_content);
        tvFrom= (TextView) findViewById(R.id.tv_news_from);
        tvTime= (TextView) findViewById(R.id.tv_news_time);
        tvTitle= (TextView) findViewById(R.id.tv_news_title);
        tvUrl= (TextView) findViewById(R.id.tv_news_url);
        tvKeyWords= (TextView) findViewById(R.id.tv_news_keywords);

        btDelete=findViewById(R.id.bt_delete);
        btDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                NewsLab.get(NewsDetailActivity.this).deleteNews(news);

            }
        });

        btSave=findViewById(R.id.bt_save);
        btSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                news.setContent(tvContent.getText().toString());
                if (tvKeyWords.getText()!=null){
                    news.setKeyWords(tvKeyWords.getText().toString());
                }
                NewsLab.get(NewsDetailActivity.this).addNews(news);
            }
        });

        btGetKeyWords=findViewById(R.id.bt_getKeyWords);
        btGetKeyWords.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (!TextUtils.isEmpty(tvContent.getText())){

                    Toast.makeText(NewsDetailActivity.this,"开始分词...",Toast.LENGTH_SHORT).show();

                    Vector<String> vector = CTAS.main(NewsDetailActivity.this,tvContent.getText().toString());
                    List<Integer> numList = new ArrayList<Integer>();
                    List<String> keyWords = new ArrayList<String>();
                    for (int i = 0; i < vector.size(); i++) {
                        if (isChinese(vector.get(i))&&vector.get(i).length()>1
                                && !keyWords.contains(vector.get(i))){
                            int num = 0;
                            for (int j = 0; j < vector.size(); j++) {
                                //统计每个分词在新闻中出现的次数
                                if (vector.get(i) .equals(vector.get(j)) ){
                                    num++;
                                }
                            }
                            keyWords.add(vector.get(i));
                            numList.add(num);
                        }
                    }
                    int temp = 0;
                    String tempString = "";
                    int size = numList.size();

                    for(int i = 0 ; i < size-1; i ++) {
                        for(int j = 0 ;j < size-1-i ; j++) {
                            if(numList.get(j) > numList.get(j+1)) {
                                //冒泡排序，将统计出的频率数，从大到小排序呢
                                temp = numList.get(j);
                                numList.set(j,numList.get(j+1));
                                numList.set(j+1,temp);

                                tempString = keyWords.get(j);
                                keyWords.set(j,keyWords.get(j+1));
                                keyWords.set(j+1,tempString);
                            }
                        }
                    }

                    Collections.sort(numList,Collections.<Integer>reverseOrder());
                    Collections.sort(keyWords,Collections.reverseOrder());
                    String  keywordscontent ="";
                    for (int i = 0; i < keyWords.size(); i++) {
                        if (i<10){
                            keywordscontent= keywordscontent+(keyWords.get(i)+"  出现频率： "+numList.get(i)+"\n");
                        }
                    }
                    tvKeyWords.setText(keywordscontent);

                }else{
                    Snackbar.make(view,"没有文章内容", Snackbar.LENGTH_SHORT).show();
                }
            }
        });

        initData();

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void initData() {

        news= (News) getIntent().getBundleExtra("news").getSerializable("news");
        tvTime .setText("发布时间："+news.getCreatedAt());
        tvFrom.setText("来源："+news.getSource());
        tvTitle.setText(news.getTitle());
        getSupportActionBar().setTitle(news.getTitle());
        tvUrl.setText(news.getUrl());
        Glide.with(this).load(news.getImage()).into(ivImage);
//        Log.d("abc","news.getContent() "+news.getContent().toString());
        if (news.getContent()==null){
            parseData(news.getUrl());
            Log.d("abc","parseData");
        }else{
            tvContent.setText(news.getContent());
        }
        if (news.getKeyWords() ==null){

        }else{
            btGetKeyWords.setVisibility(View.GONE);
            tvKeyWords.setText(news.getKeyWords());
        }

    }

    private void parseData(final String source) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                StringBuilder builder = new StringBuilder();
                try {
                    //从一个URL加载一个Document对象。
                    Document doc = Jsoup.connect(source).timeout(5000).get();
                    //获取article-content标签下的内容
                    Elements elements = doc.select("div[class=J-article-content article-content]");
                    Elements elements1 = elements.select("p");
                    //具体每一段文字内容
                    for (Element element : elements1) {

                        if (!TextUtils.isEmpty(element.text())) {
                            //把各段落文字拼接起来
                            String text = "\u3000\u3000" + element.text() + "\n\n";
                            builder.append(text);
                        }
                    }

                    //输出新闻内容
                    Message message = new Message();
                    Bundle bundle = new Bundle();
                    bundle.putString("content",builder.toString());
                    message.setData(bundle);
                    handler.sendMessage(message);


                } catch (Exception e) {
                    Log.d(TAG, e.toString());
                    builder.append(e.toString());
                }
            }
        }).start();
    }

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            tvContent.setText(msg.getData().getString("content"));
        }
    };
}
